package org.monster.context.core.manager;

import java.text.MessageFormat;
import java.util.Hashtable;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 字符串管理器
 *
 * @author Monster
 */
public class StringManager {

    /**
     * 字符串管理器 集合
     */
    private static final Hashtable<String, StringManager> managers = new Hashtable<>();
    /**
     * 资源捆绑
     */
    private final ResourceBundle bundle;
    /**
     * 语言环境
     */
    private final Locale locale;

    /**
     * 构造方法
     * 获取本地语言信息，以支持国际化
     *
     * @param packageName 包名
     */
    private StringManager(String packageName) {
        ResourceBundle b = null;
        String bundleName = packageName + ".LocalStrings";
        try {
            b = ResourceBundle.getBundle(bundleName, Locale.getDefault());
        } catch (Exception e) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (cl != null) {
                b = ResourceBundle.getBundle(bundleName, Locale.getDefault(), cl);
            }
        }
        this.bundle = b;
        if (bundle != null) {
            locale = bundle.getLocale();
        } else {
            locale = null;
        }
    }

    /**
     * 获取 管理器
     *
     * @param packageName 包名
     * @return 管理器
     */
    public static synchronized StringManager getManager(String packageName) {
        StringManager mgr = managers.get(packageName);
        if (mgr == null) {
            mgr = new StringManager(packageName);
            managers.put(packageName, mgr);
        }
        return mgr;
    }

    /**
     * 获取 字符串
     *
     * @param key 键
     * @return 值
     */
    public String getString(String key) {
        if (key == null) {
            String msg = "key值不允许为空！";
            throw new IllegalArgumentException(msg);
        }
        String str;
        try {
            str = bundle.getString(key);
        } catch (Exception e) {
            str = null;
        }
        return str;
    }

    /**
     * 获取 字符串
     *
     * @param key  键
     * @param args 参数
     * @return 值
     */
    public String getString(final String key, final Object... args) {
        String value = getString(key);
        if (value == null) {
            value = key;
        }

        MessageFormat mf = new MessageFormat(value);
        mf.setLocale(locale);

        return mf.format(args, new StringBuffer(1024), null).toString();

    }

}
